package com.czxy.changgou3.service;

import com.czxy.changgou3.mapper.AddressMapper;
import com.czxy.changgou3.pojo.Address;
import com.czxy.changgou3.pojo.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/5/4
 */
@Service
@Transactional
public class AddressService {
    @Resource
    private AddressMapper addressMapper;

    /**
     * 查询指定用户的所有地址
     * @param userId
     * @return
     */
    public List<Address> findAllByUserId(Long userId) {
        //1 拼凑条件
        Example example = new Example(Address.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        //2 查询
        return this.addressMapper.selectByExample(example);
    }

    /**
     * 添加新地址，并设置成默认地址
     * @param address
     */
    public void addAddress(User user , Address address) {
        //完善数据
        Long id = user.getId();
        Integer num = Math.toIntExact(id);
        address.setUserId(num);

        //TODO 将之前默认地址 isdefault更新为0
        this.addressMapper.updateDefault(address.getUserId(),0);

        address.setIsdefault(1);

        this.addressMapper.insert(address);
    }

}
